# Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import argparse
def read_file(args):
    bootloader_file_size = os.stat(args.blf).st_size
    app_size = os.stat(args.af).st_size
    fd1 = open(args.blf, 'rb')
    fd2 = open(args.nf, 'wb')
    buf=fd1.read(1024)
    while buf:
        fd2.write(buf)
        buf=fd1.read(1024)
    for i in range(args.asp * 1024 - bootloader_file_size):
        buf=bytes([0xff])
        fd2.write(buf)
    fd3 = open(args.af, 'rb')
    buf=fd3.read(1024)
    while buf:
        fd2.write(buf)
        buf=fd3.read(1024)
    for i in range(args.fsp * 1024 - app_size):
        buf=bytes([0xff])
        fd2.write(buf)
    print("fg is", args.fs)
    if(args.fs):
        print("start to pack", args.fs)
        fd4 = open(args.fs, 'rb')
        buf=fd4.read(1024)
        while buf:
            fd2.write(buf)
            buf=fd4.read(1024)
        fd4.close()
    fd1.close()
    fd2.close()
    fd3.close()
def cmd_parse():
    parser=argparse.ArgumentParser()
    parser.add_argument('--blf',help='bootloader file path',required=True)
    parser.add_argument('--af',help='app file path',required=True)
    parser.add_argument('--nf',help='new file path',required=True)
    parser.add_argument('--asp',help='app start position,Unit: KB',type=int,default=64)
    parser.add_argument('--fs',help='file sysytem image path')
    parser.add_argument('--fsp',help='file sysytem position,Unit: KB',type=int,default=1984)
    #parser.print_help()
    args = parser.parse_args()
    return args
read_file(cmd_parse())
